package com.lnu_devteam.zongce.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.lnu_devteam.zongce.common.ErrorCode;
import com.lnu_devteam.zongce.exception.BusinessException;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

/**
 * @author xbaozi
 * @version 1.0
 * @classname OssUtils
 * @date 2023-03-25  14:37
 * @description Oss文件上传工具类
 */
public class OssUtils {

    private static final long SIZE_M = 1024 * 1024;

    private static final long MAXIMUM = 2 * SIZE_M;

    /**
     * @description 批量上传文件
     * @author xbaozi
     * @date 2023/3/25 21:21
     * @return List<String>
     **/
    public static List<String> uploadBatch(List<MultipartFile> fileList, int maxBatchSize, OSS ossClient, String bucketName, String marketHost) throws BusinessException {
        if (fileList == null || fileList.isEmpty()) {
            throw new BusinessException(ErrorCode.UPLOAD_ERROR, "file is not allow empty");
        }
        if (fileList.size() > maxBatchSize) {
            throw new BusinessException(ErrorCode.UPLOAD_ERROR, "the number of uploaded files exceeds the limit");
        }
        List<String> fileUrlList = new ArrayList<>(maxBatchSize);
        for (MultipartFile multipartFile : fileList) {
            System.out.println("照片的大小" + multipartFile.getSize());
            if (multipartFile.getSize() > MAXIMUM) {
                throw new BusinessException(ErrorCode.UPLOAD_ERROR, "the image was rejected because its size exceeds maximum(2M)");
            }
            if (!isImage(multipartFile)) {
                throw new BusinessException(ErrorCode.UPLOAD_ERROR, multipartFile.getName() + ": only support image upload");
            }
        }
        String dir = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        for (MultipartFile multipartFile : fileList) {
            String cloudFileName = new SimpleDateFormat("HH:mm:ss").format(new Date()) +
                    "-" + UUID.randomUUID().toString().replaceAll("-", "") +
                    getExtensionName(multipartFile);
            String cloudPath = dir + "/" + cloudFileName;
            try {
                PutObjectResult res = ossClient.putObject(bucketName, cloudPath, multipartFile.getInputStream());
                if (res == null) {
                    throw new BusinessException(ErrorCode.UPLOAD_ERROR, "file upload failed");
                }
                fileUrlList.add(marketHost + "/" + cloudPath);
            } catch (IOException e) {
                throw new BusinessException(ErrorCode.UPLOAD_ERROR, "file upload failed");
            }
        }
        return fileUrlList.isEmpty() ? Collections.emptyList() : fileUrlList;
    }

    /**
     * @param imageFile 需要判断的文件
     * @description 判断文件是否为图片
     * @author xbaozi
     * @date 2022/9/13 13:25
     **/
    public static boolean isImage(File imageFile) {
        if (!imageFile.exists()) {
            return false;
        }
        Image img = null;
        try {
            img = ImageIO.read(imageFile);
            return img != null && img.getWidth(null) > 0 && img.getHeight(null) > 0;
        } catch (Exception e) {
            return false;
        } finally {
            img = null;
            imageFile.delete();
        }
    }

    /**
     * @param multipartFile 需要判断的文件
     * @description 判断文件是否为图片
     * @author xbaozi
     * @date 2023/3/25 14:41
     **/
    public static boolean isImage(MultipartFile multipartFile) {
        File file = multipartFileToFile(multipartFile);
        if (file == null || !file.exists()) {
            return false;
        }
        return isImage(file);
    }

    /**
     * @description MultipartFile转File
     * @param multipartFile 需要转换的文件
     * @author xbaozi
     * @date 2022/9/13 13:33
     **/
    public static File multipartFileToFile(MultipartFile multipartFile) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            return null;
        }
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        File file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
        try {
            OutputStream os = Files.newOutputStream(file.toPath());
            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * @description 获取文件后缀名
     * @author xbaozi
     * @date 2023/3/25 14:45
     * @param filename  文件名
     * @return String   文件后缀名，如.png
     **/
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot);
            }
        }
        return filename;
    }

    /**
     * @description 获取文件后缀名
     * @author xbaozi
     * @date 2023/3/25 14:49
     * @param file  指定文件
     * @return String   文件后缀名，如.png
     **/
    public static String getExtensionName(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return null;
        }
        return getExtensionName(file.getOriginalFilename());
    }

}
